package com.ekingstar.framework.security;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.security.Authentication;
import org.springframework.security.BadCredentialsException;
import org.springframework.security.event.authentication.AuthenticationFailureBadCredentialsEvent;
import org.springframework.security.event.authentication.InteractiveAuthenticationSuccessEvent;
import org.springframework.security.ui.WebAuthenticationDetails;

import com.ekingstar.framework.domain.OnlineUser;
import com.ekingstar.framework.domain.SystemLog;
import com.ekingstar.framework.domain.User;
import com.ekingstar.framework.service.IOnlineUserService;
import com.ekingstar.framework.service.ISystemLogService;
import com.ekingstar.framework.service.IUserService;
import com.ekingstar.framework.util.NetTools;

/**
 * 
 * 
 */
public class ApplictionLoginListener implements ApplicationListener {
	
	private static Logger log = LoggerFactory.getLogger(ApplictionLoginListener.class);

	
	private ISystemLogService systemLogService;
	private IOnlineUserService onlineUserService;
	private IUserService userService;
	
	private static int contextRefreshedEvent_num = 0;
	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.context.ApplicationListener#onApplicationEvent(org.springframework.context.ApplicationEvent)
	 */
	public void onApplicationEvent(ApplicationEvent event) {
		if (event instanceof InteractiveAuthenticationSuccessEvent) {
			InteractiveAuthenticationSuccessEvent ie = (InteractiveAuthenticationSuccessEvent) event;
			Authentication au = ie.getAuthentication();
			User user = (User) au.getPrincipal();
			if (user != null){
				userService.clearErrorCount(user.getId());
			}
			OnlineUser onlineUser = new OnlineUser();
			SystemLog systemLog = new SystemLog();
			systemLog.setTime(new Date());// sl.setTime(new Date(ie.getTimestamp()));
			systemLog.setIp(((WebAuthenticationDetails) au.getDetails())
					.getRemoteAddress());
			systemLog.setType(SystemLog.LogType.login.name());
			systemLog.setModelName("系统管理");
			systemLog.setDescription("登陆系统成功");
			systemLog.setUserId(user.getId());

			String sessionId = ((WebAuthenticationDetails) au.getDetails())
					.getSessionId();
			
			onlineUser.setIpAddress(((WebAuthenticationDetails) au.getDetails())
					.getRemoteAddress());
			onlineUser.setLoginTime(new Date());
			//String userid = user.getId();
			onlineUser.setTUser(user);
			onlineUser.setUserName(user.getName());
			onlineUser.setState("1");
			onlineUser.setSessionId(sessionId);
			if(user.getLoginTimes() == null){
				user.setLoginTimes(0);
			}
			user.setLastloginTime(onlineUser.getLoginTime());
			user.setLoginIp(onlineUser.getIpAddress());
			user.setLoginTimes(user.getLoginTimes()+1);
			this.userService.saveUser(user);
			this.onlineUserService.addUser(onlineUser);
			this.systemLogService.addLoginLog(systemLog);
			

		} else if (event instanceof AuthenticationFailureBadCredentialsEvent) {
			AuthenticationFailureBadCredentialsEvent ae = (AuthenticationFailureBadCredentialsEvent) event;
			Authentication au = ae.getAuthentication();
			
			BadCredentialsException be = (BadCredentialsException) ae
					.getException();
			User user = (User) be.getExtraInformation();
			if (au != null && au.getPrincipal() != null){
					if (user != null){
						userService.getPwdErrorCount(user.getId(), true);
					}
			}
			SystemLog systemLog = new SystemLog();

			systemLog.setTime(new Date());// systemLog.setTime(new
											// Date(ie.getTimestamp()));
			systemLog.setIp(((WebAuthenticationDetails) au.getDetails())
					.getRemoteAddress());
			systemLog.setType("login");
			systemLog.setModelName("系统管理");
			systemLog.setDescription("登陆系统失败");
			systemLog.setUserId(user.getId());
			this.systemLogService.addLoginLog(systemLog);
		} else if (event instanceof ContextRefreshedEvent) {
			// ContextRefreshedEvent ce = (ContextRefreshedEvent)event;
			if(contextRefreshedEvent_num == 0){
				SystemLog systemLog = new SystemLog();
				systemLog.setModelName("系统管理");
				systemLog.setTime(new Date());// systemLog.setTime(new Date(ie.getTimestamp()));
				systemLog.setIp(NetTools.getLocalHostIP());
				systemLog.setType("appstart");
				systemLog.setDescription("系统启动ip:"+NetTools.getAllLocalHostIPStr());
				//log.info("abc");
				//log.info("abc"+NetTools.getAllLocalHostIPStr());
				//log.info("abc");
				this.onlineUserService.deleteAllData();
				//log.info("abc");
				this.systemLogService.addLoginLog(systemLog);
			}
			contextRefreshedEvent_num++;
		}
	}
	
	public IUserService getUserService() {
		return userService;
	}


	public void setUserService(IUserService userService) {
		this.userService = userService;
	}


	public ISystemLogService getSystemLogService() {
		return systemLogService;
	}

	public void setSystemLogService(ISystemLogService systemLogService) {
		this.systemLogService = systemLogService;
	}
	public IOnlineUserService getOnlineUserService() {
		return onlineUserService;
	}
	public void setOnlineUserService(IOnlineUserService onlineUserService) {
		this.onlineUserService = onlineUserService;
	}
	
}
